<template>
  <div class="app-container">
    <!-- 申请类型;1:普通领用;2:换型领用 -->
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="产品">
          <el-select
            v-model="searchParam.currentProductId"
            placeholder="请选择产品"
            @keyup.enter="search"
            clearable
          >
            <el-option
              v-for="item in productList"
              :key="`${item.id}`"
              :label="`${item.productName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="领用人">
          <SelectPerson
            :maxCollapseTags="5"
            :isMultiple="false"
            :width="`100%`"
            placeholder="请选择领用人"
            :showSelectPerson="selectPersonData"
            @get-person="getPerson"
          />
        </el-form-item>
        <el-form-item label="申请日期">
          <el-date-picker
            v-model="searchParam.applyDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getapplyDate"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetHandle"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="单据号"
          prop="recordCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品"
          prop="currentProductName"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="领用部门"
          prop="receiveDepartmentName"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="领用人"
          prop="receivePersonName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="申请日期"
          prop="applyDate"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div>
              {{ dayjs(scope.row.applyDate).format("YYYY-MM-DD") || "" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="申请原因"
          prop="applyReason"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <use-apply-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable } from "@/utils/useTable";
import request from "@/utils/request";
import dayjs from "dayjs";

defineOptions({
  name: "EAMMTUSEAPPLY",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/eammtuseapply/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  applyType: 1,
  receivePersonId: "",
  changeProductId: "",
  applyDateSearch: [],
  applyDateStart: "",
  applyDateEnd: "",
};

const deleteParam = {
  api: "/eam/eammtuseapply/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

function resetHandle() {
  selectPersonData.value = [];
  reset();
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getProductList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eammtuseapply/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开器具领用申请表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改领用申请";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增领用申请";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开器具领用申请表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "领用申请详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getapplyDate(data: any) {
  if (data) {
    searchParam.value.applyDateStart = data[0];
    searchParam.value.applyDateEnd = data[1];
  } else {
    searchParam.value.applyDateStart = "";
    searchParam.value.applyDateEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eammtuseapply/deleteItem/${id}`,
      method: "post",
    });
    ElMessage.success("删除成功");
    search();
  });
}

// 获取产品信息下拉树
const productList: any = ref([]);
const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmproductinfo/getList",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  productList.value = data;
};

// 打开人员选择器方法
const selectPersonData: any = ref([]);
function getPerson(Ids: string[], Objects: any) {
  searchParam.value.receivePersonId = Objects[0]?.id || "";
}
</script>
